package com.qianfeng.openapi.web.master.controller;

import com.qianfeng.openapi.web.master.bean.AjaxResponse;
import com.qianfeng.openapi.web.master.bean.TableData;
import com.qianfeng.openapi.web.master.pojo.AdminUser;
import com.qianfeng.openapi.web.master.pojo.Menu;
import com.qianfeng.openapi.web.master.service.MenuService;
import com.qianfeng.openapi.web.master.utils.Constacts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @Author LJF
 * @Date 2020/7/1 17:12
 * @Version 1.0
 */
@RestController
@RequestMapping("/sys/menu")
@CrossOrigin(allowCredentials = "true")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/side")
    public AjaxResponse side(HttpSession session, HttpServletResponse response) throws IOException {
        //获取登录的用户session
        AdminUser adminUser = (AdminUser) session.getAttribute(Constacts.LOGIN_ADMIN_USER);
        if(adminUser==null){
            response.sendRedirect("login.html");
            return null;
        }
        //得到用户的id
        Integer id = adminUser.getId();
        return new AjaxResponse(true,null,menuService.findMenuByUid(id));
    }

    @RequestMapping("/list")
    public TableData<Menu> getMenus(){
        List<Menu> menuList = menuService.getAllMenu();
        return new TableData<Menu>((long) menuList.size(),menuList);
    }

    @RequestMapping("/tree")
    public List<Menu> tree(){
        return menuService.getMenuTree();
    }

    @RequestMapping("/info")
    public Menu info(Integer id){
        return menuService.getMenuById(id);
    }

    @RequestMapping("/add")
    public AjaxResponse add(Menu menu){
        try{
            menuService.insertMenu(menu);
            return new AjaxResponse(true,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResponse(false,"添加失败");
        }
    }

    @RequestMapping("/update")
    public AjaxResponse update(Menu menu){
        try{
            menuService.updateMenu(menu);
            return new AjaxResponse(true,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResponse(false,"添加失败");
        }
    }

    @RequestMapping("/delete")
    public AjaxResponse delete(Integer[] ids){
        try{
            menuService.deleteMenus(ids);
            return new AjaxResponse(true,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResponse(false,"添加失败");
        }
    }
}
